package com.ztom.daily.n2022.m4;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * 迷你语法解析器
 * <p>
 * https://leetcode-cn.com/problems/mini-parser/
 *
 * @author ZhangTao
 */
public class Day15NestedInteger {

    // This is the interface that allows for creating nested lists.
// You should not implement it, or speculate about its implementation
    class NestedInteger {
        // Constructor initializes an empty nested list.
        public NestedInteger() {
        }

        // Constructor initializes a single integer.
        public NestedInteger(int value) {
        }

        // @return true if this NestedInteger holds a single integer, rather than a nested list.
        public boolean isInteger() {
            return false;
        }

        // @return the single integer that this NestedInteger holds, if it holds a single integer
        // Return null if this NestedInteger holds a nested list
        public Integer getInteger() {
            return 0;
        }

        // Set this NestedInteger to hold a single integer.
        public void setInteger(int value) {

        }

        // Set this NestedInteger to hold a nested list and adds a nested integer to it.
        public void add(NestedInteger ni) {

        }

        // @return the nested list that this NestedInteger holds, if it holds a nested list
        // Return empty list if this NestedInteger holds a single integer
        public List<NestedInteger> getList() {
            return new ArrayList<>();
        }
    }

    public NestedInteger deserialize(String s) {
        if (s == null || s.length() == 0) {
            return null;
        }

        // 开头不是 [ 说明无嵌套
        if (s.charAt(0) != '[') {
            return new NestedInteger(Integer.parseInt(s));
        }

        Deque<NestedInteger> stack = new LinkedList<>();
        int curNum = 0;
        boolean isNegative = false;
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == '-') {
                isNegative = true;
            } else if (Character.isDigit(c)) {
                curNum = curNum * 10 + (c - '0');
            } else if (c == '[') {
                stack.offerLast(new NestedInteger());
            } else if (c == ',' || c == ']') {
                // 当前数字读取完毕
                if (Character.isDigit(s.charAt(i - 1))) {
                    if (isNegative) {
                        curNum *= -1;
                    }
                    stack.peekLast().add(new NestedInteger(curNum));
                }
                curNum = 0;
                isNegative = false;
                // 如果是 ] 而前面有多个 [ 需要将当前 [] 加入前面的 [
                if (c == ']' && stack.size() > 1) {
                    NestedInteger cur = stack.pollLast();
                    stack.peekLast().add(cur);
                }
            }
        }
        return stack.pollLast();
    }
}
